package com.sname.demoribbon.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author 宋贤坤
 * @date 2018/11/15 17:35
 */
@RestController
@RequestMapping
public class ConsumerController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    // ribbon进行负载均衡的客户端
    // loadBalancerClient加载实例,获取服务器的地址之类的

    @RequestMapping("/consumer1")
    public String helloConsumerOne() {
        ServiceInstance instance = loadBalancerClient.choose("stores");
        // 此处的stores是配置文件"stores.ribbon.listOfServices=localhost:8081,localhost:8082"的第一个节点
        URI uri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
        // "http://%s:%s"是URL编码的所以这样写,上面的代码是把Http头带上
        // host和port是动态的;是负载均衡分配过后的;此处的uri是已经经过负载均衡的请求了
        return uri.toString();
    }


    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/consumer2")
    public String helloConsumerTwo() {
        // 通过restTemplate来搞定
        System.out.println("begin");
        String result = restTemplate.getForEntity("http://DEMO-UPMS/user/hello", String.class).getBody();
        return result;
    }

    @RequestMapping("/list")
    public Object lalala() {
        Object body = restTemplate.getForEntity("http://DEMO-UPMS/user/list", String.class).getBody();

        return body;
    }

}